package com.haina.vote.controller;

import com.haina.vote.entity.Project;
import com.haina.vote.service.impl.SpiderService;
import com.haina.vote.utils.FileDownloader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/spider")
public class SpiderController {
    @Autowired
    private SpiderService spiderService;
    @RequestMapping("/findAll")
    public String findAll(Project projectModel){
        List<Project> projects=spiderService.findAll(projectModel);
        for (Project project : projects) {
           String fl= project.getFile_list();
           String recuuid=project.getRecUuid();
           if (!StringUtils.isEmpty(fl)){
               String[] sfl=fl.split(",");
               String filename=null;
               String filepath="D:\\采集数据附件\\自然科学基金申报指南";
               System.out.println(sfl);
               if (sfl.length>1){
                   Project project_update1=new Project();
                   String resfilename="";
                   for (String s : sfl) {
                       filename=UUID.randomUUID().toString().replace("-","")+s.substring(s.lastIndexOf("."));
                       File resfile=FileDownloader.saveUrlAs(s,filepath,filename,"GET");
                       String fpath=resfile+"/"+filename;
                       File checkFilePath=new File(fpath);
                       if (checkFilePath.exists()){
                           resfilename+=filename+",";
                           project_update1.setFile_list2(resfilename);
                           project_update1.setRecUuid(recuuid);
                       }
                   }
                   spiderService.updateProject(project_update1);
               }else {
                   filename=UUID.randomUUID().toString().replace("-","")+fl.substring(fl.lastIndexOf("."));
                  File file = FileDownloader.saveUrlAs(fl,filepath,filename,"GET");
                  String fpath=file+"/"+filename;
                  File checkFilePath=new File(fpath);
                  if (checkFilePath.exists()){
                      Project project_update=new Project();
                      project_update.setFile_list2(filename);
                      project_update.setRecUuid(recuuid);
                      spiderService.updateProject(project_update);
                  }

               }
           }else {
               System.out.println(project.getTitle().toString()+"没有附件");
           }
        }
        return "";
    }


}
